package com.fivefu.core.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.fivefu.core.pojo.FfSql;
import com.fivefu.core.parse.FfExecuteSql;
import com.fivefu.core.service.FfCacheService;
import com.fivefu.core.service.FfDataSourceService;
import com.fivefu.core.util.CachekeyUtils;
import com.fivefu.core.util.CachekeyUtils.CacheItem;
import java.time.Duration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Author zhf
 * @Description
 * @Date 2021/3/9
 */
@Service
public class RedisCacheService implements FfCacheService {

    @Autowired
    FfDataSourceService ffDataSourceService;
    @Autowired
    FfExecuteSql ffExecuteSql;
    @Autowired
    RedisTemplate redisTemplate;

    public Object getResultByKey(JSONObject json, FfSql ffSql) {
        CacheItem cacheItem = CachekeyUtils.getKeyByJson(json, ffSql);
        Object result = redisTemplate.opsForValue().get(cacheItem.getKey());
        if (null == result) {
            result = ffExecuteSql.executeFFSql(ffSql);
            redisTemplate.opsForValue().set(cacheItem.getKey(), result, Duration.ofMinutes(cacheItem.getMinutes()));

        }
        return result;
    }
}
